#!/usr/bin/python

#Built in Modules
import logging, logging.handlers, socket, subprocess
from time import sleep
import sys
sys.path.append('/usr/local/bin')
from ping import Ping # Note that ping comes from https://github.com/jedie/python-ping

class Pinger(object):
    def __init__(self,ping_target='www.google.com',ping_timeout=500,max_tries=5,sleep_time=90):
        self.ping_target  = ping_target
        self.ping_timeout = ping_timeout
        self.max_tries    = max_tries
        self.sleep_time   = sleep_time
        self.failed_pings = 0
        logger.info('Initializing pingTest.py')

    def ping_failed(self,msg='unknown'):
        self.failed_pings += 1
        logger.warning("Ping {0} to {1} failed for {2} msec: {3}".format(self.failed_pings,self.ping_target,self.ping_timeout,msg))

    def ping_succeeded(self,delay):
        logger.debug('Ping to {0} succeeded. Delay: {1}'.format(self.ping_target,delay))
        self.failed_pings = 0

    def reset_modem(self):
        logger.critical('Ping of {1} failed {1} times.  Resetting modem.'.format(self.max_tries,self.ping_target))
        result = subprocess.call("/home/avp/bin/cyclemodem.sh", shell=True)
        sleep(self.sleep_time)
        return result

    def start(self):
        logger.info('Starting pingTest.py')
        while True:     #forever
            sleep(self.sleep_time)
            try:
                delay = Ping(self.ping_target, timeout=self.ping_timeout).do()
                if delay:
                    self.ping_succeeded(delay)
                else:
                    self.ping_failed('timeout')
            except socket.error, e:
                self.ping_failed(e)
            except Exception, e:
                self.ping_failed(e)
            if self.failed_pings >= self.max_tries:   # Try resetting modem
                self.reset_modem()

if __name__ == '__main__':
    ping_target  = 'www.google.com'
    ping_timeout = 5000 # ms
    max_tries    = 5
    sleep_time   = 90     # seconds

    logger = logging.getLogger('pingTest.py')

    #logger.setLevel(logging.DEBUG)
    logger.setLevel(logging.INFO)  # uncomment to suppress debug messages

    hdlr      = logging.handlers.SysLogHandler(address='/dev/log', facility=logging.handlers.SysLogHandler.LOG_DAEMON)
    formatter = logging.Formatter('%(filename)s: %(levelname)s: %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)

    p = Pinger(ping_target,ping_timeout,max_tries,sleep_time)
    p.start()

